package com.jc.task.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by yaojie.cao 2017/3/8.
 */
@Service
public class RedisUtil {

    private static Logger logger = LoggerFactory.getLogger(RedisUtil.class);

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${task.redis.key}")
    private String redisTaskKey;

    public static Map<String, String> REDIS_TASK_MAP;

    private HashOperations<String, String, String> hashOperations;

    private HashOperations<String, String, String> gethashOperations() {
        if (hashOperations == null) {
            hashOperations = redisTemplate.opsForHash();
        }
        return hashOperations;
    }

    @PostConstruct
    public void init() {//所有的序列化都走 String
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new StringRedisSerializer());
    }


    public Map<String, String> getRedisTaskMap(boolean refresh) {
        if (REDIS_TASK_MAP == null || refresh) {//为null 或者 需要刷新才查询，减轻查询
            REDIS_TASK_MAP = redisTemplate.boundHashOps(redisTaskKey).entries();
        }
        return REDIS_TASK_MAP;
    }

    /**
     * 设置key
     *
     * @param jobDetailName
     * @param bodyParameter
     */
    public synchronized void set(String jobDetailName, String bodyParameter) {
        gethashOperations().put(redisTaskKey, jobDetailName, bodyParameter);
    }

    /**
     * 设置key
     *
     * @param jobDetailName
     */
    public synchronized String get(String jobDetailName) {
        return gethashOperations().get(redisTaskKey, jobDetailName);
    }

    /**
     * 删除key
     *
     * @param jobDetailName
     */
    public synchronized void del(String jobDetailName) {
        gethashOperations().delete(redisTaskKey, jobDetailName);
    }

    /**
     * 获取是Date任务
     *
     * @return
     */
    public List<JSONObject> getDateAll(String searchingKey, boolean refresh) {
        List<JSONObject> resultList = new ArrayList(3000);
        Map<String, String> resultMap = getRedisTaskMap(refresh);
        for (Map.Entry<String, String> entry : resultMap.entrySet()) {
            String jsonStr = entry.getValue();
            JSONObject jsonObject = JSON.parseObject(jsonStr);
            jsonObject.put("key", entry.getKey());
            if (jsonObject.getDate("date") != null) {
                jsonObject.put("createDate", dateFormat.format(jsonObject.getDate("createDate")));
                jsonObject.put("date", dateFormat.format(jsonObject.getDate("date")));
                if (!StringUtils.isEmpty(searchingKey)) {
                    if (searchingKey.equals(entry.getKey()) || jsonStr.indexOf(searchingKey) > -1) {
                        resultList.add(jsonObject);
                    }
                } else {
                    resultList.add(jsonObject);
                }
            }
        }
        resultList.sort(new Comparator<JSONObject>() {//兼容Jdk 1.7
            @Override
            public int compare(JSONObject o1, JSONObject o2) {
                return o2.getDate("createDate").compareTo(o1.getDate("createDate"));
            }
        });
        return resultList;
    }

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 获取是Cron任务
     *
     * @return
     */
    public List<JSONObject> getCronAll(String searchingKey, boolean refresh) {
        List<JSONObject> resultList = new ArrayList(3000);
        Map<String, String> resultMap = getRedisTaskMap(refresh);
        for (Map.Entry<String, String> entry : resultMap.entrySet()) {
            String jsonStr = entry.getValue();
            JSONObject jsonObject = JSON.parseObject(jsonStr);
            jsonObject.put("key", entry.getKey());
            if (jsonObject.getString("cronExpression") != null) {
                jsonObject.put("createDate", dateFormat.format(jsonObject.getDate("createDate")));
                if (!StringUtils.isEmpty(searchingKey)) {
                    if (searchingKey.equals(entry.getKey()) || jsonStr.indexOf(searchingKey) > -1) {
                        resultList.add(jsonObject);
                    }
                } else {
                    resultList.add(jsonObject);
                }
            }
        }
        resultList.sort(new Comparator<JSONObject>() {//兼容Jdk 1.7
            @Override
            public int compare(JSONObject o1, JSONObject o2) {
                return o2.getDate("createDate").compareTo(o1.getDate("createDate"));
            }
        });
        return resultList;
    }

    /**
     * 获取所有的值
     *
     * @return
     */
    public Set<String> getKeys() {
        return gethashOperations().keys(redisTaskKey);
    }

}
